package com.cskaoyan.servlet;

import com.cskaoyan.annotation.WdAutowired;
import com.cskaoyan.annotation.WdMapping;
import com.cskaoyan.service.UserService;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author stone
 * @date 2022/11/13 22:59
 */
@WebServlet("/user/*")
public class UserServlet extends HttpServlet {

    @WdAutowired
    UserService userService;

    Map<String,Method> uriMethod = new HashMap<>();

    @Override
    public void init() throws ServletException {
        fieldInitialization();//给成员变量做赋值

        methodInitialization(); // 建立uri和method之间的映射关系
    }

    private void methodInitialization() {
        Method[] methods = this.getClass().getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(WdMapping.class)) {
                WdMapping declaredAnnotation = method.getDeclaredAnnotation(WdMapping.class);
                String suffix = declaredAnnotation.value();
                uriMethod.put(suffix, method);
            }
        }
    }

    private void fieldInitialization() {
        ServletContext servletContext = getServletContext();
        ApplicationContext applicationContext = (ApplicationContext) servletContext.getAttribute("applicationContext");

        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            boolean annotationPresent = field.isAnnotationPresent(WdAutowired.class);
            if (annotationPresent) {
                Class<?> type = field.getType(); // UserService.class
                Object bean = applicationContext.getBean(type);
                field.setAccessible(true);
                try {
                    field.set(this,bean);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();//  /user/*
        WebServlet declaredAnnotation = this.getClass().getDeclaredAnnotation(WebServlet.class);
        String[] value = declaredAnnotation.value();
        int length = value[0].length() - 1;
        int endIndex = requestURI.length();
        String suffix = requestURI.substring(length, endIndex);
        Method method = (Method) uriMethod.get(suffix);
        try {
            method.invoke(this, new Object[]{resp});
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @WdMapping("hello")
    private void sayHello(HttpServletResponse resp) throws IOException {
        resp.getWriter().write("hello world");
    }
    @WdMapping("goodbye")
    private void sayGoodbye(HttpServletResponse resp) throws IOException {
        resp.getWriter().write("别了，司徒雷登");
    }
}
